package itbour.onetouchshow.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;

import itbour.onetouchshow.utils.DisplayUtil;

/**
 * Created by guoh on 2018/7/9.
 * 功能描述：正常的TextView旋转之后显示有问题 因此自定义一个旋转显示的TextView
 * 需要的参数：
 */
public class RotateTextView extends View {
    private int mWidth;
    private int mHeight;
    private String text = "0s";

    public RotateTextView(Context context) {
        this(context, null);
    }

    public RotateTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void setText(String text) {
        this.text = text;
        this.invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();
        // 改变控件的宽高
        setMeasuredDimension(mHeight, mWidth);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 改变Canvas坐标系，使文字在竖直方向绘制
        canvas.translate(mHeight, 0);
        canvas.rotate(90);

        Rect rect = new Rect(0, 0, mHeight, mWidth);

        TextPaint textPaint = new TextPaint();
        textPaint.setColor(Color.WHITE);
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setTextSize(DisplayUtil.sp2px(getContext(), 14));
        textPaint.setTextAlign(Paint.Align.CENTER);

        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        //为基线到字体上边框的距离,即上图中的top
        float top = fontMetrics.top;
        //为基线到字体下边框的距离,即上图中的bottom
        float bottom = fontMetrics.bottom;

        //基线中间点的y轴计算公式
        int baseLineY = (int) (rect.centerY() - top / 2 - bottom / 2);

        canvas.drawText(text, rect.centerX(), baseLineY, textPaint);
    }
}